﻿using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WinServer.MainByNF461
{
    public class HttpServer
    {
        private HttpListener httpListener;
        private ConcurrentQueue<string> MessageQueue { set; get; }

        public HttpServer()
        {
            httpListener = new HttpListener();
            MessageQueue = new ConcurrentQueue<string>();
        }

        public void Start(string ip = "*", int port = 8095)
        {
            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            //如果发送到8053 端口没有被处理，则这里全部受理，+是全部接收
            var url = string.Format("http://*:{0}/", port);
            httpListener.Prefixes.Add(url);
            httpListener.Start();//开启服务

            Console.WriteLine(string.Format("Http Listener On {0}", url));
            httpListener.BeginGetContext(new AsyncCallback(ListenerHandle), httpListener);
        }

        public void Stop()
        {
            httpListener.Stop();
        }

        private void ListenerHandle(IAsyncResult result)
        {
            httpListener = result.AsyncState as HttpListener;
            if (httpListener != null && httpListener.IsListening)
            {
                HttpListenerContext context = httpListener.EndGetContext(result);
                httpListener.BeginGetContext(new AsyncCallback(ListenerHandle), httpListener);

                _ = ExecuteAsync(context);
            }

        }

        private async Task ExecuteAsync(HttpListenerContext context)
        {
            await Task.Run(() =>
            {
                var sendBack = new ResponseData() { Success = true, Message = "成功" };
                try
                {
                    //解析Request请求
                    HttpListenerRequest request = context.Request;
                    string content = "";

                    if (request.RawUrl.ToLower().StartsWith("/ws/senddata"))
                    {
                        if (request.HttpMethod.ToUpper() == "POST")
                        {
                            Stream stream = context.Request.InputStream;
                            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                            content = reader.ReadToEnd();
                            MessageQueue.Enqueue(string.Format("{0}==>{1}",DateTime.Now.ToString("MM-dd HH:mm:ss"), content));
                        }

                        ResponseData(context, 200, JsonConvert.SerializeObject(sendBack));
                    }
                    else if (request.RawUrl.ToLower().StartsWith("/ws/getdata"))
                    {
                        if(MessageQueue.TryDequeue(out content))
                        {
                            sendBack.Message = content;
                        }
                        else
                        {
                            sendBack.Message = "队列中暂无数据";
                        }

                        ResponseData(context, 200, JsonConvert.SerializeObject(sendBack));
                    }
                    else
                    {
                        ResponseData(context, 404, "");
                    }

                }
                catch (Exception ex)
                {
                    sendBack.Success = false;
                    sendBack.Message = ex.Message;
                    ResponseData(context, 200, JsonConvert.SerializeObject(sendBack));
                }
            });
        }

        private void ResponseData(HttpListenerContext context, int statusCode, string data)
        {
            HttpListenerResponse response = context.Response;
            response.StatusCode = statusCode;
            response.ContentType = "application/json;charset=UTF-8";
            response.ContentEncoding = Encoding.UTF8;
            response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
            response.AppendHeader("Access-Control-Allow-Origin", "*");//跨域支持

            using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
            {
                writer.Write(data);
                writer.Close();
                response.Close();
            }
        }
    }
}
